package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {

    @Value("${nologin.urls}")
    private String urls;

    AntPathMatcher matcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        //配置需要放行的资源
        String[] loginUrls = urls.split(",");

        String uri = request.getRequestURI();

        for (String loginUrl : loginUrls) {
            if(matcher.match(loginUrl, uri)){
                filterChain.doFilter(request,servletResponse);
                return;
            }
        }

        //判断是否已登录
        Employee loginUser = (Employee) request.getSession().getAttribute("loginUser");
        if(loginUser != null){

            BaseContext.setCurrentId(loginUser.getId());
            filterChain.doFilter(request,servletResponse);//放行
            BaseContext.remove();
            return;
        }
        //判断是否已登录(手机验证码登录)
        User user = (User) request.getSession().getAttribute("user");
        if(user != null){
            BaseContext.setCurrentId(user.getId());
            filterChain.doFilter(request,servletResponse);//放行
            BaseContext.remove();
            return;
        }

        //未登录,非放行资源
        R r = R.error("NOTLOGIN");
        String jsonString = JSON.toJSONString(r);
        servletResponse.getWriter().write(jsonString);

    }

}
